from django.shortcuts import *
from django.views.generic import View,TemplateView
from django.core.exceptions import ImproperlyConfigured
from django.core.paginator import Paginator
from django.contrib.auth.models import User
from django.contrib import auth
from django.contrib.auth.decorators import login_required
from .models import *

DEFAULT_PAGE_SIZE=20
# Create your views here.

# class SingleFromView(TemplateView):
#     from_class=None
#     def __init__(self,*args,**kwargs):
#         if not self.from_class:
#             raise ImproperlyConfigured("SingleFromView require from_class")
#         if not self.extra_context:
#             self.extra_context={}
#         else:
#             self.extra_context['from']=from_class
#         super().__init__(self,*args,**kwargs)
def login(request):
    message=None
    error=None
    if request.method=='POST':
        username=request.POST.get('username')
        password=request.POST.get('password')
        user=auth.authenticate(request,username=username,password=password)
        if user:
            auth.login(request,user)
            return redirect(request.GET.get('next') or reverse('index'))
        error='登录失败'
    return render(request,'login.html',{
        'message':message,
        'error':error
        })
@login_required
def logout(request):
    auth.logout(request)
    return redirect(reverse('login'))
@login_required
def user(request):
    message=None
    error=None
    if request.method=='POST':
        raw=request.POST.get('password_raw')
        new_pass=request.POST.get('password_new')
        repeat=request.POST.get('password_repeat')
        if new_pass!=repeat:
            error="两次密码输入不一致"
        elif new_pass==raw:
            error="新密码不能与原密码相同"
        elif request.user.check_password(raw):
            if len(new_pass)<5:
                error="密码长度太短"
            else:
                request.user.set_password(new_pass)
                request.user.save()
                message="修改成功"
        else:
            error="密码错误"

    return render(request,'user.html',{
        "message":message,
        "error":error
    })
def register(request):
    message=None
    error=None
    if request.method=='POST':
        try:
            username=request.POST.get('username')
            password=request.POST.get('password')
            email=request.POST.get('email')
            user=User.objects.create_user(username,email=email,password=password)
            user.set_password(password)
            user.save()
            return redirect(reverse('login'))
        except:
            error="注册失败"
    return render(request,'register.html',{
        'message':message,
        'error':error
        })

@login_required
def index(request):
    page=int(request.GET.get('page',1))
    size=int(request.GET.get('size',DEFAULT_PAGE_SIZE))
    name=request.GET.get('name',None)
    queryset=Product.objects.all()
    if name:
        queryset=queryset.filter(title__contains=name)
    paginator=Paginator(queryset.order_by('title'),size)
    return render(request,'index.html',{
        "paginator":paginator.page(page),"page":page
    })
@login_required
def cart(request):
    page=int(request.GET.get('page',1))
    size=int(request.GET.get('size',DEFAULT_PAGE_SIZE))
    name=request.GET.get('name',None)
    queryset=get_or_init_cart(request.user).items.all()
    error=None
    if queryset.count()==0:
        error='当前购物车为空'
    if name:
        queryset=queryset.filter(product__title__contains=name)
    queryset=queryset.order_by('product')
    paginator=Paginator(queryset,size)
    
    return render(request,'cart.html',{
        "error":error,
        "total":sum(i.total for i in get_or_init_cart(request.user).items.all()),
        "paginator":paginator.page(page),"page":page,
        "query_string":name
    })
@login_required
def add_internal(request,product,count):
    cart,created=Cart.objects.get_or_create(account=request.user)
    item,created=cart.items.get_or_create(product=product,defaults={"counts":0})
    item.counts+=count
    item.save()
@login_required
def show(request,pk):
    message=None
    error=None
    product=get_object_or_404(Product,pk=pk)
    if request.method=='POST' or request.GET.get('add'):
        count=int(request.POST.get('count',1))
        if count:
            add_internal(request,product,count)
            message='已成功添加%s个到购物车'%(count)
        else:
            error='数量不能为零'
    return render(request,'show.html',{
        "product":product,
        'message':message,
        'error':error
    })
@login_required
def add(request,pk):
    return redirect(reverse('show',args=(pk,))+'?add=true')
    # product=get_object_or_404(Product,pk=pk)
    # add_internal(request,product,1)
    # return render(request,'show.html',{
    #     "product":product,
    #     'message':'已成功添加到购物车'
    # })
@login_required
def delete(request,pk):
    product=get_object_or_404(Product,pk=pk)
    get_or_init_cart(request.user).items.filter(product=product).delete()
    return redirect(reverse('cart'))
@login_required
def clear(request):
    get_or_init_cart(request.user).items.all().delete()
    return redirect(reverse('cart'))
@login_required
def payit(request):
    cart=get_or_init_cart(request.user)
    queryset=cart.items.all()
    if request.method=='POST':
        address=int(request.POST.get('address'))
        address=get_object_or_404(Address, pk=address,account=request.user)
        order=Order(account=request.user,address=address,price=sum(i.total for i in queryset))
        order.save()
        order.items.set(queryset)
        cart.items.clear()
        order.save()
        return redirect(reverse('order',args=(order.pk,)))
    if queryset.count()==0:
        return redirect(reverse('cart'))
    page=int(request.GET.get('page',1))
    size=int(request.GET.get('size',DEFAULT_PAGE_SIZE))
    name=request.GET.get('name','').strip()
    if name:
        queryset=queryset.filter(product__title__contains=name)
        
    paginator=Paginator(queryset.order_by('product'),size)
    address=Address.objects.filter(account=request.user)
    return render(request,'payit.html',{
        "address":address,
        "paginator":paginator.page(page),"page":page,
        "total":sum(i.total for i in cart.items.all()),
        "query_string":name
    })
@login_required
def order(request,pk):
    order=get_object_or_404(Order,pk=pk,account=request.user)
    queryset=order.items.all()
    page=int(request.GET.get('page',1))
    size=int(request.GET.get('size',DEFAULT_PAGE_SIZE))
    name=request.GET.get('name','').strip()
    if name:
        queryset=queryset.filter(product__title__contains=name)
    queryset=queryset.order_by('product__title')
    paginator=Paginator(queryset,size)
    return render(request,'order.html',{
        "order":order,
        "paginator":paginator.page(page),
        "query_string":name,
        "page":page
    })
@login_required
def order_del(request,pk):
    order=get_object_or_404(Order,pk=pk)
    order.delete()
    return redirect(reverse('orders'))
@login_required
def address(request):
    message=None
    error=None
    if request.method=='POST':
        location=int(request.POST.get('location'))
        location=get_object_or_404(Location,code=location)
        detail=request.POST.get('detail').strip()
        address,created=Address.objects.get_or_create(account=request.user,location=location,detail=detail)
        address.save()
        if created:
            message='成功添加地址'
        else:
            error='地址已存在'
    queryset=Address.objects.filter(account=request.user)
    page=int(request.GET.get('page',1))
    size=int(request.GET.get('size',DEFAULT_PAGE_SIZE))
    name=request.GET.get('name','').strip()
    if name:
        queryset=queryset.filter(detail__contains=name)
    locations=Location.objects.all()
    paginator=Paginator(queryset.order_by('location'),size)
    return render(request,'address.html',{
        "message":message,
        "locations":locations,
        "error":error,
        "paginator":paginator.page(page),
        "query_string":name,
        "page":page
    })
@login_required
def address_modify(request,pk):
    address=get_object_or_404(Address,account=request.user,pk=pk)
    locations=Location.objects.all()
    message=None
    error=None
    if request.method=='POST':
        address.location=get_object_or_404(Location,code=int(request.POST.get('location',0)))
        address.detail=request.POST.get('detail').strip()
        if Address.objects.filter(location=address.location,detail=address.detail).count():
            error="地址已存在"
        else:
            address.save()
            message='保存成功'
    return render(request,'address-modify.html',{
        'locations':locations,
        'address':address,
        'message':message,
        "error":error
    })

@login_required
def address_delete(request,pk):
    address=get_object_or_404(Address,account=request.user,pk=pk)
    address.delete()
    return redirect(reverse('address'))
@login_required
def orders(request):
    error=None
    message=None
    queryset=Order.objects.filter(account=request.user)
    page=int(request.GET.get('page',1))
    size=int(request.GET.get('size',DEFAULT_PAGE_SIZE))
    name=request.GET.get('name','').strip()
    if name:
        queryset=queryset.filter(address__detail__contains=name)
    paginator=Paginator(queryset.order_by('address'),size)
    return render(request,'orders.html',{
        'paginator':paginator.page(page),
        "query_string":name,
        "message":message,
        "error":error
    })